<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 05/09/2017
 * Time: 22:32
 */
namespace frontend\controllers;

use common\models\ar\MoneyChangeDirection;
use common\models\ar\MoneyWithdraw;
use common\models\ar\RealName;
use common\models\ar\SysConfig;
use common\models\ar\UserMoney;
use common\models\MoneyDao;
use common\models\Pay;
use common\models\RechargeDao;
use common\models\WithdrawDao;
use common\models\ar\MoneyOrder;
use common\models\ar\ExchangeRate;
class MoneyController extends FrontendController
{
    public $enableCsrfValidation = false;
    /**
     * 资金变更记录
     */
    public function actionHistory()
    {
        $uid = \Yii::$app->user->identity->userID;
        $req = \Yii::$app->request;
        $isRender = $req->get('isRender', 1);
        $direction = $req->get('direction', -1);//变更类型
        //资金类型
        $tmp = MoneyChangeDirection::find()->where(['level_5_show_flag' => 1])->asArray()->all();
        $directions = [];
        foreach ($tmp as $v) {
            $directions[$v['id']] = $v;
        }

        if ($direction != -1) {
            $direction = [$direction];
        }

        $from = $req->get('from', date('Ymd', time() - 7 * 24 * 3600));
        $to = $req->get('to', date('Ymd'));
        $from = strtotime($from);
        $to = strtotime($to) + 24 * 3600;

        $pageNo = $req->get('pageNo', 1);
        $pageSize = 15;

        $data = MoneyDao::history($direction, -1, -1, $uid, $from, $to, $pageNo, $pageSize);
        $pageTotal = ceil($data['total'] / $pageSize);
        if ($pageTotal == 0) {
            $pageNo = 1;
        } else {
            if ($pageNo > $pageTotal) {
                $pageNo = $pageTotal;
                $data = MoneyDao::history($direction, -1, -1, $uid, $from, $to, $pageNo, $pageSize);
            }
        }

        $data['from'] = $from;
        $data['to'] = $to - 1;
        $data['directions'] = $directions;
        $data['pageNo'] = $pageNo;
        $data['pageTotal'] = ceil($data['total'] / $pageSize);

        if ($isRender == 1) {
            return $this->renderPartial('history', $data);
        } else {
            exit(json_encode($data));
        }
    }

    /**
     * 充值
     *
     * @return string
     */
    public function actionRecharge()
    {
        $req = \Yii::$app->request;
        $from = $req->get('from', date('Ymd', time() - 7 * 24 * 3600));
        $to = $req->get('to', date('Ymd'));
        $from = strtotime($from);
        $to = strtotime($to) + 24 * 3600;
        //获取汇率值
        $RMB=ExchangeRate::findOne(['currency'=>'RMB']);
        $RMB=$RMB['exchange_rate'];
        //充值费率
        $tmp = SysConfig::find()->where(['key' => 'recharge_rate'])->asArray()->one();
        $rechargeRemark = "充值费率：";
        if (!$tmp) {
            $rechargeRemark .= "8";
        } else {
            $rechargeRemark .= $tmp['value'] * $tmp['percent'];
        }
        $rechargeRemark .= "‰，此费用由 \"第三方支付\" 收取";

        return $this->renderPartial('recharge', [
            'from' => $from,
            'to' => $to,
            'rechargeRemark' => $rechargeRemark,
            'RMB'=>$RMB
        ]);
    }
    /**
     * 本次充值记录
     */
    public function actionRechargeSubmit()
    {
        $req = \Yii::$app->request;
        $money_order=$req->post('money_order','');
        $moneys=$req->post('moneys','0');
        $uid = \Yii::$app->user->identity->userID;
        $order=date('ymdhms',time()).rand(100,999);
        $time=date(time());
        $moneyorder = new MoneyOrder();
        $moneyorder->userID=$uid;
        $moneyorder->user_type=1;
        $moneyorder->money_order=$order;
        $moneyorder->time=$time;
        $moneyorder->value=$money_order;
        $moneyorder->moneys=$moneys;
        $moneyorder->save(false);
        if ($moneyorder->save(false)) {
            $code = 1;
            $msg = "请求成功";
        } else {
            $code = 0;
            $msg = "请求失败";
        }
        exit(json_encode(['code' => $code, 'msg' => $msg, 'order' => $order]));
    }


    /**
     * 跳转到第三方支付的表单
     */
    public function actionRechargePayForm()
    {
        $uid = \Yii::$app->user->identity->userID;

        $rechargeSN = \Yii::$app->request->get('order', '');
        var_dump($rechargeSN);
        exit();
        $sql = "SELECT
                    a.*
                FROM
                    `money_recharge` a
                WHERE  a.`recharge_sn` = :recharge_sn 
                AND a.`userID` = $uid
        ";
        $res = \Yii::$app->db->createCommand($sql, [':recharge_sn' => $rechargeSN])->queryOne();
        if (!$res) {
            exit("request error!");
        }
        $money=$res['money']*100;
        $money=str_pad($money,12,'0',STR_PAD_LEFT);
        $payParams = \Yii::$app->params['sand_pay'];
        $data = [
            'head'=>[
                'version'=>$payParams['version'],
                'method'=>$payParams['method'],
                'productId'=>$payParams['productId'],
                'mid' => $payParams['mid'], //商户号
                'accessType' =>$payParams['accessType'], //普通商户
                'channelType'=>$payParams['channelType'],
                'reqTime'=>$payParams['reqTime'],
            ],
            'body'=>[
                'orderCode' => $rechargeSN,
                'txnTimeOut'=>$payParams['txnTimeOut'],
                'totalAmount'=>$money,//订单金额
                'payMode' =>$payParams['payMode'], // 支付模式
                'payExtra'=>$payParams['payExtra'],
                'clientIp'=>$payParams['clientIp'],//客户端 IP 
                'frontUrl' => $payParams['frontUrl'], // 提交支付请求后同步回调url
                'notifyUrl' => $payParams['notifyUrl'], // 异步回调url
                'subject' => $payParams['subject'], // 订单标题
                'body' => $payParams['body'], // 订单描述 
                'extend'=>$payParams['extend'],
             ]
        ];
        $pay = new Pay();
        $keys=$pay->loadPk12Cert($pay::PRI_KEY_PATH,$pay::CERT_PWD);
        $sign=$pay->sign($data,$keys);
        $post= array(
            'charset' =>'utf-8',
            'signType'=>'01',
            'data'=>json_encode($data),
            'sign'=>$sign
         );
        //$data=json_encode($data);
        //post请求
        $result=$pay->http_post_json($payParams['api']['recharge'],$post);

        $arr=$pay->parse_result($result);

        //step5: 公钥验签
         $pubkey =$pay->loadX509Cert($pay::PUB_KEY_PATH);
            try {
                verify($arr['data'], $arr['sign'], $pubkey);
            } catch (\Exception $e) {
                echo $e->getMessage();
                exit;
            }

            // step6： 获取credential
            $data = json_decode($arr['data'], true);
            if ($data['head']['respCode'] == "000000") {
                $credential = $data['body']['credential'];
                //var_dump($credential);
                //exit();
                return $this->renderPartial('recharge-SanDepay-form', ['url' =>'', 'credential' => $credential]);
                // var_dump( $credential);
                // exit();
            } else {
                print_r($arr['data']);
            }
        }
        // else {
        //     echo "不是POST传输  ";
        // } 
        //return $this->renderPartial('recharge-pay-form', ['url' => $payParams['api']['recharge'], 'post' => $data]);

    /**
     * 第三方支付跳回后需要显示给客户
     */
    public function actionRechargeReturn()
    {
        $rechargeSN = \Yii::$app->request->get('order', '');
        return $this->renderPartial("/money/recharge");
    }

    /**
     * 充值历史
     */
    public function actionRechargeHistory()
    {

        $uid = \Yii::$app->user->identity->userID;
        $req = \Yii::$app->request;
        $status = $req->get('status', -1);//充值状态
        $from = $req->get('from', date('Ymd', time() - 7 * 24 * 3600));
        $to = $req->get('to', date('Ymd'));
        $from = strtotime($from);
        $to = strtotime($to) + 24 * 3600;
        $pageNo = $req->get('pageNo', 1);
        $pageSize = 15;
        $data = RechargeDao::history($status, $uid, $from, $to, $pageNo, $pageSize);

        $pageTotal = ceil($data['total'] / $pageSize);
        if ($pageTotal == 0) {
            $pageNo = 1;
        } else {
            if ($pageNo > $pageTotal) {
                $pageNo = $pageTotal;
                $data = RechargeDao::history($status, $uid, $from, $to, $pageNo, $pageSize);
            }
        }
        $data['pageNo'] = $pageNo;
        $data['pageTotal'] = $pageTotal;
        exit(json_encode($data));
    }

    /**
     * 出金
     *
     * @return string
     */
    public function actionWithdraw()
    {
        $req = \Yii::$app->request;
        $from = $req->get('from', date('Ymd', time() - 7 * 24 * 3600));
        $to = $req->get('to', date('Ymd'));
        $from = strtotime($from);
        $to = strtotime($to) + 24 * 3600;
        $RMB=ExchangeRate::findOne(['currency'=>'RMB']);
        $RMB=$RMB['exchange_rate'];
        return $this->renderPartial('withdraw', [
            'from' => $from,
            'to' => $to,
            'RMB'=>$RMB
        ]);
    }

    /**
     * 提交出金
     */
    public function actionWithdrawSubmit()
    {
        $req = \Yii::$app->request;
        $uid = \Yii::$app->user->identity->userID;
        $longinNames=\Yii::$app->user->identity->loginName;
        $money = $req->post('money', 0);
        $money = sprintf("%.2f",$money);
        //是否已做实名信息
        $tmp = RealName::findOne($uid);
        if (!$tmp || $tmp->status != 1) {
            $code = 1001;
            $msg = "账户实名未完成，请至 `实名验证` 页面提交您的实名信息";
            $msg=$msg."<strong style='font-size:20px;'><a href='/user/info-real-name'>点击实名</a></strong>";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        //有未处理的记录
//        $sql = "SELECT COUNT(1) FROM `money_withdraw` WHERE `userID` = $uid AND `status` = 0";
//        $count = \Yii::$app->db->createCommand($sql)->queryScalar();
//        if ($count != 0) {
//            $code = '1007';
//            $msg = "您有未处理的出金记录";
//            exit(json_encode(['code' => $code, 'msg' => $msg]));
//        }
        //当日出金次数限制
        $today = strtotime(date('Ymd'));
        $tmp = SysConfig::find()->where(['key' => 'max_withdraw_times'])->one();
        $maxTimes = $tmp->value;
        $tmp = SysConfig::find()->where(['key' => 'max_withdraw_money'])->one();
        $maxMoney = $tmp->value;

        //当日已出金次数
        $sql = "SELECT COUNT(1) FROM `money_withdraw` WHERE `userID` = $uid AND `withdraw_open_time` >= $today AND `status` = 3";
        $count = \Yii::$app->db->createCommand($sql)->queryScalar();
        if ($count >= $maxTimes) {
            $code = '1008';
            $msg = "每日出金次数限制为 " . $maxTimes . " 次";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        if (!is_numeric($money) || !$money) {
            $code = 1004;
            $msg = "请输入正确的出金金额";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if ($money < 10) {
            $code = 1005;
            $msg = "出金金额不能小于10元";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if ($money > $maxMoney) {
            $code = 1005;
            $msg = "出金金额不能大于" . $maxMoney . "元";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        //持仓或未生效的委托检测
        $sql="SELECT COUNT(1) FROM `hold_positions` WHERE `userID` = '".$uid."' ";
         $bool = \Yii::$app->db->createCommand($sql)->queryScalar();
         if ($bool!=0) {
             $code = '1004';
             $msg = "账户有持仓或未生效的委托";
             exit(json_encode(['code' => $code, 'msg' => $msg]));
         }
        //出金最大资金额
            $tmp = UserMoney::findOne(['userID'=>$uid]);
            $totalMoney = $tmp['totalMoney'];
        if ($totalMoney < $money) {
            $code = '1007';
            $msg = "账户单笔最大可出金额为：" . $totalMoney;
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $time = time();
        $ip = $req->getUserIP();
        $ua = $req->getUserAgent();
        $direction = 8; //出金
        $type = 2; //$money < $maxMoney ? 1 : 2;//1直接调代付接口,2由后台审核后调代付接口

        //记录
        $withdrawSN = uniqid('W');
        $withdrawObj = new MoneyWithdraw();
        $withdrawObj->attributes = [
            'withdraw_sn' => $withdrawSN,
            'userID' => $uid,
            'direction' => $direction,
            'money' => $money,
            'status' => 0,
            'withdraw_open_time' => $time,
            'loginName'=>$longinNames,
        ];
        if (!$withdrawObj->save(false)) {
            $code = '1007';
            $msg = "出金失败 | -" . $code;
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        //判断用户资金信息
         $bool = MoneyDao::inOut($uid, $uid, $direction, $money, $time, 1, $ip, $ua, '客户出金');
         if (!$bool) {
             $withdrawObj->status = 2;
             $withdrawObj->save();
             $code = '1010';
             $msg = "出金失败 | -" . $code;
             exit(json_encode(['code' => $code, 'msg' => $msg]));
         }
        //调用代付接口
        if ($type == 1) {
            $payObj = new Pay();
            $return = $payObj->withdraw($withdrawObj->id);

            if ($return['code'] == '000000') {
                $code = 1;
                $msg = "出金成功";
                $withdrawObj->status = 3;
            } else {
                $code = 0;
                $msg = "出金失败 | " . $return['code'];
                $withdrawObj->status = 2;
            }
            $withdrawObj->resp_code = $return['code'];
            $withdrawObj->withdraw_end_time = time();
            $withdrawObj->data_response = json_encode($return);
            $withdrawObj->save();

        } else {
            $code = '1';
            $msg = "出金已提交";
        }
        exit(json_encode(['code' => $code, 'msg' => $msg]));
    }

    /**
     * 取消出金
     */
    public function actionWithdrawCancel()
    {
        $uid = \Yii::$app->user->identity->userID;
        $id = \Yii::$app->request->get('id', 0);
        $obj = MoneyWithdraw::findOne($id);
        if (!$obj || $obj->userID != $uid) {
            $code = 1001;
            $msg = '权限不足';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if ($obj->status != 0) {
            $code = 1002;
            $msg = '状态已变化';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        switch ($obj->direction) {
            case 2:
                $direction = 1;
                break;
            case 8:
                $direction = 9;
                break;
            case 18:
                $direction = 17;
                break;
            case 102:
                $direction = 101;
                break;
            default:
                $code = 1003;
                $msg = '类型错误';
                exit(json_encode(['code' => $code, 'msg' => $msg]));
                break;
        }

        $time = time();
        $ip = \Yii::$app->request->getUserIP();
        $ua = \Yii::$app->request->getUserAgent();

        $bool = MoneyDao::inOut($uid, $uid, $direction, $obj->money, $time, 1, $ip, $ua, '用户取消');
        if (!$bool) {
            $code = 0;
            $msg = "操作失败";
        } else {
            $obj->status = 5;
            $obj->withdraw_start_time = $time;
            $obj->withdraw_end_time = $time;
            $obj->data_response = json_encode(['msg' => '用户取消']);
            $obj->save(false);
            $code = 1;
            $msg = "操作成功";
        }

        exit(json_encode(['code' => $code, 'msg' => $msg]));
    }

    /**
     * 出金历史
     */
    public function actionWithdrawHistory()
    {
        $uid = \Yii::$app->user->identity->userID;
        $req = \Yii::$app->request;
        $status = $req->get('status', -1);//状态

        $from = $req->get('from', date('Ymd', time() - 7 * 24 * 3600));
        $to = $req->get('to', date('Ymd'));
        $from = strtotime($from);
        $to = strtotime($to) + 24 * 3600;

        $pageNo = $req->get('pageNo', 1);
        $pageSize = 15;
        $data = WithdrawDao::history($status, $uid, $from, $to, $pageNo, $pageSize);
        $pageTotal = ceil($data['total'] / $pageSize);
        if ($pageTotal == 0) {
            $pageNo = 1;
        } else {
            if ($pageNo > $pageTotal) {
                $pageNo = $pageTotal;
                $data = WithdrawDao::history($status, $uid, $from, $to, $pageNo, $pageSize);
            }
        }
        $data['pageNo'] = $pageNo;
        $data['pageTotal'] = $pageTotal;

        exit(json_encode($data));
    }
}
